package com.cal.utms.action.user_maintenance;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.cal.utms.core.MenuModel;
import com.cal.utms.dao.user_maintenance.UserDaoImpl;
import com.cal.utms.dto.user_maintenance.LoginDto;
import com.cal.utms.entity.User;
import com.cal.utms.model.user_maintenance.UserModel;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class LoginAction extends ActionSupport implements ModelDriven<LoginDto>, SessionAware {

	/**
	 * 
	 */

	private static final long serialVersionUID = 1L;
	private LoginDto loginDto = new LoginDto();
	UserDaoImpl daoImpl = new UserDaoImpl();
	MenuModel menuModel = new MenuModel();
	private static Map<String, Object> session;

	public String login() {
		String user_name = loginDto.getUser().trim().toUpperCase();
		String password = null;
		try {
			password = UserModel.encrypt(loginDto.getPassword().trim());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
		User user = daoImpl.getUserByUsername(user_name);
		if (user != null) {
			if (password.equals(user.getPassword())) {
				loginDto.setSuccess(true);
				loginDto.setResultMsg("1");
				session.put("loginId", user.getUserName());
				session.put("userGroup", user.getUserGroup().getId());
				session.put("user", user);
			} else {
				loginDto.setResultMsg("3");
				loginDto.setSuccess(false);
			}
		} else {
			loginDto.setResultMsg("2");
			loginDto.setSuccess(false);
		}

		return Action.SUCCESS;
	}

	@Override
	public LoginDto getModel() {
		return loginDto;
	}

	public LoginDto getLoginModel() {
		return loginDto;
	}

	public void setLoginModel(LoginDto loginModel) {
		this.loginDto = loginModel;
	}

	@Override
	public void setSession(Map<String, Object> arg0) {
		this.session = arg0;

	}

	public static User getCurrentLogingUser() {
		User user = (User) session.get("user");
		return user;
	}
}
